<?php

namespace App\Http\Controllers\Api\V1;


use App\Http\Resources\BooksResource;
use App\Models\Books;
use Illuminate\Http\Request;

/***
 * 书籍列表
 * Class BooksController
 * @package App\Http\Controllers\Api\V1
 */
class BooksController extends ApiController
{
    //获取书籍列表
    public function getlist(Request $request, Books $books)
    {
        $query = $books->newQuery();
        $modelId = $request->input('module_id', null);
        if ($modelId) {
            $query->where('module_id', $modelId);
            $query->whereNotIn('status', [0, 1]);
            if ($request->has('type_id') && is_array($request->type_id)) {

                $query->where(function ($querys) use ($request) {
                        foreach ($request->type_id as $typeid) {
                            $querys->orwhere('type_id', 'like', '%' . $typeid . '%');
                        }
                    });

            }
            if ($request->has('keyword') && !empty($request->keyword)) {
                $query->where('name', 'LIKE', '%' . $request->keyword . '%');
            }
            //排序
            switch ($request->order) {
                case 1:
                    $query->orderBy('view_num', 'desc');
                    break;//点击数
                case 2:
                    $query->orderBy('like_num', 'desc');
                    break;//点赞数
                case 3:
                    $query->orderBy('comment_num', 'desc');
                    break;//评论数
                case 4:
                    $query->orderBy('share_num', 'desc');
                    break;//分享数
                case 5:
                    $query->orderBy('collect_num', 'desc');
                    break;//收藏数
                case 6:
                    $query->orderBy('is_top', 'desc');
                    break;//置顶大小
                default:
                    $query->orderBy('updated_at', 'desc');//不传按更新时间排序
            }
            $list = $query->with(['user', 'bookscore'])->paginate();
            return $this->success('成功', BooksResource::collection($list));
        } else {
            $this->error('参数错误');
        }
    }

    public function getBookinfo(Request $request, Books $books)
    {
        $query = $books->newQuery();
        $modelId = $request->input('module_id', null);
        if ($modelId) {
            $query->where('module_id', $modelId);
            $query->whereNotIn('status', [0, 1]);

            if ($request->has('book_id') && !empty($request->book_id)) {
                $query->where('id', $request->book_id);
            }
            $list = $query->with('user')->paginate();
            return $this->success('成功', BooksResource::collection($list));
        } else {
            $this->error('参数错误');
        }
    }
}
